<template>
  <fks-dialog
    width="960px"
    class="export-dialog"
    :title="title"
    :visible.sync="dialogVisible"
    @close="close"
  >
    <div slot="title">
      <i
        v-if="this.type == 'import'"
        v-permission="['menu:import']"
        class="fks-icon-import"
      />
      <i
        v-if="this.type == 'export'"
        v-permission="['menu:export']"
        class="fks-icon-export"
      />
      {{ this.title }}
    </div>
    <div class="main">
      <fks-form ref="form" label-width="0px">
        <fks-form-item v-if="type == 'export'" :span="24">
          <span class="import-tip">{{ LANG.CONFIRM_MENU }}</span>
        </fks-form-item>
        <fks-form-item v-if="type == 'export'">
          <template>
            <fks-table
              :data="tableData"
              row-key="id"
              heigth="500px"
              default-expand-all
            >
              <fks-table-column
                :label="LANG.NAME"
                prop="title"
                header-align="center"
                width="350"
                align="left"
                size="mini"
              >
                <template slot-scope="scope">
                  {{ LANG[scope.row.title] || scope.row.title }}
                </template>
              </fks-table-column>
              <fks-table-column
                :label="LANG.ROUTEPATH"
                prop="path"
                header-align="center"
                width="350"
                align="left"
              />
              <fks-table-column :label="LANG.ICON" prop="icon" align="center">
                <template slot-scope="scope">
                  <fks-icon
                    v-if="scope.row.icon"
                    :icon-class="scope.row.icon"
                  />
                </template>
              </fks-table-column>
              <fks-table-column
                :label="LANG.SORT"
                prop="content.sort"
                align="center"
              />
            </fks-table>
          </template>
        </fks-form-item>
        <fks-form-item v-if="type == 'import'" :span="12">
          <span class="import-tip">{{ LANG.IMPORT_PARENT_MENU }}</span>
          <span class="import-tip">「{{ choosedMenu }}」</span>
          <span v-if="importParentMenu.length == 0" class="import-tip"
            >,{{ LANG.IMPORT_DEFAULT_TIP }}</span
          >
        </fks-form-item>
        <fks-form-item
          v-if="type == 'import' && exportMenuList.length <= 1"
          :span="12"
        >
          <span class="import-tip">{{ LANG.UPLOAD_TIP }}</span>
        </fks-form-item>
        <fks-form-item
          v-show="!expandFlag && type == 'import' && menuTreeData.length > 0"
          :span="12"
        >
          <div style="" class="tree-container">
            <fks-tree
              ref="tree"
              :data="menuTreeData"
              show-checkbox
              node-key="id"
              :check-strictly="true"
              highlight-current
              @check="checkData"
            >
              <template slot-scope="{ data }">
                {{ LANG[data.content.title] || data.content.title }}
              </template>
            </fks-tree>
          </div>
        </fks-form-item>
        <fks-form-item
          v-if="type == 'import' && exportMenuList.length <= 1"
          :span="12"
        >
          <fks-upload
            ref="upload"
            :class="{
              'menu-upload-expanded': menuTreeData.length == 0,
              'menu-upload-shrink': menuTreeData.length > 0,
            }"
            :action="uploadUrl"
            drag
            name="file"
            :headers="{
              'Fawkes-Auth': ACESS_TOKEN,
            }"
            :with-credentials="true"
            :auto-upload="false"
            :limit="1"
            accept=".json"
            :file-list="fileList"
            :http-request="submit"
          >
            <div>
              <i class="fks-icon-upload" />
              <div class="fks-upload__text">
                {{ LANG.DRAG_FILE_TIP }}
                <em>{{ LANG.CLICK_UPLOAD }}</em>
                <br />
                <span>{{ LANG.FILE_FORMAT }}</span>
              </div>
            </div>
          </fks-upload>
        </fks-form-item>
      </fks-form>
    </div>
    <div slot="footer">
      <fks-button
        v-if="type == 'export'"
        type="primary"
        icon="fks-icon-check"
        @click="exportMenu"
      >
        {{ LANG.EXPORT }}
      </fks-button>
      <fks-button
        v-if="type == 'import'"
        type="primary"
        icon="fks-icon-check"
        :disabled="exportMenuList.length > 1"
        @click="importMenu"
      >
        {{ LANG.IMPORT }}
      </fks-button>
    </div>
  </fks-dialog>
</template>
<script>
import { importMenu, exportMenu } from "../../api";
import { exportFile } from "@/utils/file";
import { treeToArray } from "@/utils/array";
export default {
  name: "MenuImportExoprt",
  props: {
    type: {
      type: String,
      default: "import",
    },
    visible: {
      type: Boolean,
      default: false,
    },
    exportMenuList: {
      type: Array,
      default: [],
    },
    menuTreeData: {
      type: Array,
      default: [],
    },
    portal: {
      type: Object,
      default() {
        return {};
      },
    },
  },
  data() {
    return {
      choosedMenu: "根菜单",
      expandFlag: false,
      defaultProps: {
        children: "children",
        label: "label",
      },
      dialogVisible: this.visible,
      ACESS_TOKEN: this.$storage.get("access_token"),
      uploadUrl: "",
      fileList: [],
      tableData: [],
      importParentMenu: [],
    };
  },
  computed: {
    title() {
      switch (this.type) {
        case "export":
          return this.LANG.EXPORT_CONFIG;
        default:
          return this.LANG.IMPORT_CONFIG;
      }
    },
  },
  watch: {
    visible() {
      this.dialogVisible = this.visible;
    },
    exportMenuList: {
      deep: true,
      immediate: true,
      handler(val) {
        this.tableData = val;
        if (val.length) {
          this.importParentMenu = val;
          this.choosedMenu = this.LANG[val[0].title] || val[0].title;
          this.$nextTick(() => {
            this.$refs.tree?.setCheckedNodes(val);
          });
        }
      },
    },
  },
  mounted() {},
  methods: {
    checkData(node, checkedData) {
      if (
        this.importParentMenu.length > 0 &&
        this.importParentMenu[0]?.id == node.id
      ) {
        this.importParentMenu = [];
        this.choosedMenu = "根菜单";
        this.$refs.tree.setCheckedNodes([]);
      } else {
        this.importParentMenu = [node];
        this.$refs.tree.setCheckedNodes([node]);
        this.choosedMenu = this.LANG[node.content.title] || node.content.title;
      }
    },

    close() {
      this.$emit("update:visible", false);
    },
    //上传导入文件
    submit(params) {
      let pid =
        this.importParentMenu.length == 0 ? "0" : this.importParentMenu[0].id;
      let form = new FormData();
      //文件对象
      form.append("parentId", pid ?? "0");
      form.append("type", this.portal.type ?? "");
      if (this.portal.portalId) {
        form.append("portalId", this.portal.portalId);
        form.append("isGeneral", false);
      } else {
        form.append("isGeneral", true);
      }
      form.append("file", params.file);
      importMenu(form)
        .then((res) => {
          if (res.status) {
            this.resolveResData(res.data);
          }
        })
        .catch(() => {});
    },
    resolveResData(responseData) {
      let menuArray = [];
      let errorList = [];
      let delMenuData = [];
      delMenuData = this.resoleTableData(responseData, true);
      menuArray = treeToArray(delMenuData);
      errorList = menuArray.filter((item) => {
        return item.importErrorMsg;
      });
      this.$nextTick(() => {
        this.close();
      });
      if (errorList.length > 0) {
        this.$message.error(this.LANG.IMPORT_ERROR);
        this.$emit(
          "showErrorTip",
          responseData,
          errorList.length == menuArray.length
        );
      } else {
        this.$message.success(this.LANG.SUCCESS);
      }
      this.fileList = [];
      this.$emit("fetchData");
    },
    resoleTableData(menuErrorData, flag) {
      menuErrorData.forEach((item) => {
        if (item.importErrorMsg) {
          if (item.children) {
            item.children.forEach((val) => {
              val.importErrorMsg = this.LANG.PARENT_MENU_IMPORT_ERROR;
              if (val.children) {
                this.resoleTableData(val.children, false);
              }
            });
          }
        } else {
          if (!flag) {
            item.importErrorMsg = this.LANG.PARENT_MENU_IMPORT_ERROR;
            if (item.children) {
              this.resoleTableData(item.children, false);
            }
          } else {
            if (item.children) {
              this.resoleTableData(item.children, true);
            }
          }
        }
      });
      return menuErrorData;
    },
    //导出数据
    exportMenu() {
      exportMenu(this.tableData)
        .then((res) => {
          if (res.status) {
            this.$message.success(this.LANG.EXPORT_SUCCESS);
            exportFile(res);
            this.tableData = [];
            this.close();
          } else {
            this.$message.error(this.LANG.EXPORT_ERROR);
          }
        })
        .catch(() => {});
    },

    //导入菜单文件
    importMenu() {
      this.$refs.upload.submit();
    },
  },
};
</script>
<style lang="scss" scoped>
.tree-container {
  position: relative;
  box-sizing: border-box;
  width: 440px;
  height: 300px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  overflow: auto;
  text-align: center;
  background-color: #fff;
  cursor: pointer;

  &:hover {
    border: 1px dashed var(--theme-color);
  }
}

.import-tip {
  font-size: 14px;
  color: #191919;
}

.menu-upload-expanded {
  ::v-deep .fks-upload-dragger {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 896px;
    height: 200px;
  }

  ::v-deep .fks-icon-upload {
    margin: 0 !important;
  }
}

.menu-upload-shrink {
  ::v-deep .fks-upload-dragger {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 440px;
    height: 300px;
  }

  ::v-deep .fks-icon-upload {
    margin: 0 !important;
  }
}
</style>